package org.momo.rpc.client.impl;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.momo.rpc.exception.RpcCallException;
import org.momo.rpc.protocol.RpcMessage;
import org.momo.rpc.protocol.RpcRequest;
import org.momo.rpc.protocol.constant.MessageType;

public class ChannelWriteListener implements ChannelFutureListener {

    private final Object data;

    private final RpcMessage.Header header;

    public ChannelWriteListener(RpcMessage message) {
        this.header = message.getHeader();
        this.data = message.getData();
    }

    @Override
    public void operationComplete(ChannelFuture channelFuture) {
        if (!channelFuture.isSuccess()) {
            UnprocessedRequest.remove(header.getId());
            String errorMsg = String.format("Send message error! the error is {}", channelFuture.cause().getMessage());

            if (MessageType.getMessageTypeEnumByCode(header.getMessageType()) == MessageType.REQUEST) {
                RpcRequest request = (RpcRequest) data;
                throw new RpcCallException(header.getId(), request.getServiceName(), request.getMethodName(), false, errorMsg);
            }
        }
    }

}
